// 修改报错统一格式
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';

// 直接用Catch指定 HttpException, 修改返回响应式
@Catch(HttpException)
export class CustomExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const response = host.switchToHttp().getRequest<Response>();

    response.statusCode = exception.getStatus();

    // 获取在下一层里面的响应data可以拿到具体的内容
    const res = exception.getResponse() as { message: string[] };

    response
      .json({
        code: exception.getStatus(),
        message: 'fail',
        data: res?.message?.join(',') || exception.message,
      })
      .end();
  }
}
